package demo;

import org.json.JSONObject;

import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.api.request.TmcUserPermitRequest;
import com.taobao.api.response.TmcUserPermitResponse;

public class TradeCreate {

	public static void main(String[] args) {
		String appKey = "1021820838";
		String appSecret = "sandbox2a3b4dbc7f7139ac4d7304bdf";
//		final String sessionKey = "6100514c989b9e3202e9af1e58de9777de922c64deeceff3638380614";
		final String sessionKey = "6100607bbdac6d319c8771b7ec60d1832cc9a683165bddc3638380614";
		String serverUrl = "http://gw.api.tbsandbox.com/router/rest";

		// TmcClient client = new TmcClient(appKey, appSecret,"default");
		TmcClient client = new TmcClient("ws://mc.api.tbsandbox.com/", appKey,
				appSecret, "default");

		final TaobaoClient tbClient = new DefaultTaobaoClient(serverUrl,
				appKey, appSecret);
		final TradeFullinfo tf = new TradeFullinfo();

		client.setMessageHandler(new MessageHandler() {
			public void onMessage(Message message, MessageStatus status) {
				try {
					System.out.println("receive a message!");
					String jsonMessage = message.getContent();
					JSONObject jsonObject = new JSONObject(jsonMessage);
					// long tid = 192385102046705L;
					long tid = jsonObject.getLong("tid");
					System.out.println("tid：" + tid);
					System.out.println(jsonMessage);
					System.out.println(message.getTopic());
					// 默认不抛出异常则认为消息处理成功

					tf.execute(tbClient, sessionKey, tid);
				} catch (Exception e) {
					e.printStackTrace();
					status.fail();// 消息处理失败回滚，服务端需要重发
				}
			}
		});
		try {
			client.connect();
			long min10 = 1000 * 30;
			Thread.sleep(min10);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

//		 DefaultTaobaoClient client = new DefaultTaobaoClient(serverUrl,
//		 appKey,
//		 appSecret);
//		 TmcUserPermitRequest req = new TmcUserPermitRequest();
//		 req.setTopics("taobao_trade_TradeCreate");
//		 try {
//		 while (true) {
//		 TmcUserPermitResponse response = client
//		 .execute(req, sessionKey);
//		 System.out.println(response.getBody());
//		 System.out.println(response.getMsg());
//		 long min10 = 1000 * 30;
//		 Thread.sleep(min10);
//		 }
//		 } catch (Exception e) {
//		 // TODO Auto-generated catch block
//		 e.printStackTrace();
//		 }
	}
}
